<?php

/***************************************************************************
 * name:文件管理类
 * author: tjx
 * 环境：php5.2 + --with-zip
 * 转载请保留该信息
****************************************************************************/
class file
{
    var $dir;
	var $web_domain;
	var $allowType;
	var $allowMime;
	var $server_path;
	
	var $mEditFile;
	var $mDeleteFile;
	var $mCdnEditFile;
	var $mCdnDeleteFile;

    function file($data) 
    {
    	
		foreach ($data AS $key => $value) {
			$this->$key = $value;
		}
   
 
    }
    
    function __construct($data) {
    	
        $this->file($data);
    }
    
    
    //返回当前目录下所有文件列表
    function getFiles($dir = '') {
    	
        $arrReturn = array();
        if(empty($dir)) {
            $dir = $this->dir;
        }
        //处理文件夹信息
        if ($handle = opendir($dir)) {
        	
            while (false !== ($file = readdir($handle))) {
            	
                if ($file != "." && $file != "..") {
                	
                    if (is_dir($dir.'/'.$file)) {
                        $arrReturn['dirs'][] = $file;
                    } else {
                    	
                    	$fTime = filemtime($dir.'/'.$file); 
                    	
                        $arrReturn['files'][$fTime][] = $file;
                    }
                }
            }
            closedir($handle);
        }
       	if(	!empty($arrReturn['files'])) {
       	 	krsort($arrReturn['files']);
       	}
	
        return $arrReturn;
    }
    
    //上传文件
    function upload($src, $dir = '', $dest = '', $maxSize = 102400000, $allowType = '', $allowMime = '') {
    	
        if (empty($src)){
            return false;
        }
        
        $src = $_FILES[$src];
        
        if ($src['size'] > $maxSize) {
            return false;
        }
        
        if (empty($dir) || $dir == '') {
            $dir = $this->dir;
        }
        
        if (empty($allowType) || $allowType == '') {
            $allowType = $this->allowType;
        }
        
        if(empty($allowMime) || $allowMime == '') {
            $allowMime = $this->allowMime;
        }
        
        $arrMime = split(',', $allowMime);
        $arrType = split(',', $allowType);
        $arrFileExt = split('\.', $src['name']);
        $fileExt = $arrFileExt[count($arrFileExt)-1];
        
        if( !in_array($fileExt, $arrType) && !in_array($src['type'], $arrMime) )  {
            
            return false;
        }
        
        if (!is_dir($dir)) {
            $this->makeDir($dir);
        }
        
        if (empty($dest))  {
            $dest = basename($src['name']);
        }
   

        $fdest = $dir . '/' . $dest;
   
        if (!move_uploaded_file($src['tmp_name'],$fdest)) {
            return false;
        }
        
        $str_dir = substr_count($dir, '.') > 0 ? substr($dir, 1, strlen($dir)) : $dir;
        if (substr_count($dest, '.zip') == 0) {
            $str_dir = str_replace('//', '/', $str_dir.'/'.$dest);
          	$this->getInsertFileUrl($str_dir, '', 'edit');

        }
        
        return array('file'=>$dest, 'path'=>$dir);
    }
    
    //解压缩文件
    function unZip($src, $dir = '') {
    	
        $fdir = getcwd();
        
        if (empty($src) || !eregi("\.zip$", $src)) {
            return false;
        }
        
        if (empty($dir)) {
        	
            if ( false !== strpos($src,'/')) {
                $dir = dirname($src);
            } else {
                $dir = $this->dir;
            }
        }
        
        chdir($dir);
        $exdir = basename($src, '.zip').'/';
        $zip = zip_open($src);
        
        if ($zip) {
        	
           // @mkdir($exdir);
       
            while ($zip_entry = zip_read($zip)) {
            	
                if (zip_entry_open($zip, $zip_entry, "r")) {
                	
                    if (substr(zip_entry_name($zip_entry),-1) == '/') {
                        if (!is_dir(zip_entry_name($zip_entry))) {
                                $this->makeDir(zip_entry_name($zip_entry), './');
                        }
                    } else {
                    	
                        if(zip_entry_filesize($zip_entry) <= 0) {
                            continue;
                        }
                        
                        $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

                        $arrMime = split(',', $this->allowMime);
                        $arrType = split(',', $this->allowType);
                        $fileExt = substr(strrchr(zip_entry_name($zip_entry),'.'),1);
                        if (!in_array($fileExt, $arrType) && !in_array($src['type'], $arrMime)) {
                            continue;
                        }
                        
                        if ($fp = @fopen('./'.zip_entry_name($zip_entry),'w')) {
                        	
                            fwrite($fp, $buf);
                            fclose($fp);
                            $str_dir = substr_count($dir, '.') > 0 ? substr($dir, 1, strlen($dir)) : $dir;
                        
                            $str_dir = str_replace('//', '/', $str_dir);
                            $str_dir = str_replace('//', '/', $str_dir.'/'.zip_entry_name($zip_entry));
                            
                            $this->getInsertFileUrl($str_dir, '', 'edit');
                          
                           
                        }
                    }
                    
                    zip_entry_close($zip_entry);
                }
            }
            
            zip_close($zip);
           
        }
        chdir($fdir);
    }
    
    //创建目录
    function makeDir($dirName, $dir = '', $mod = 0777) {
    	
        if (empty($dirName)) {
            return false;
        }
        
        if(empty($dir)) {
            $dir = $this->dir;
        }
       	$dir_path = $dir.'/'.$dirName;
 		$dir_path = str_replace('.//', './', $dir_path);
 		
        return is_dir($dir_path) or ($this->makeDir(dirname($dirName),$dir, $mod) and @mkdir($dir_path, $mod));
    }
    
    //删除目录
	function deltree($pathdir)  
	{  
		
		if ($this->is_empty_dir($pathdir)) {  
			rmdir($pathdir);//直接删除  
			
		} else{ //否则读这个目录，除了.和..外  
			
			$d = dir($pathdir);  
			
			while ($a = $d->read())  {  
				
				
				if (is_file($pathdir.'/'.$a) && ($a!='.') && ($a!='..')) {
					//记删除url到文件中 
					$this->getInsertFileUrl($pathdir, $a, 'del');
					unlink($pathdir.'/'.$a);
				} 
				
				
				//如果是文件就直接删除  
				if(is_dir($pathdir.'/'.$a) && ($a!='.') && ($a!='..'))  
				{
					//如果是目录  
					if(!$this->is_empty_dir($pathdir.'/'.$a)) {//是否为空  
						
						//如果不是，调用自身，不过是原来的路径+他下级的目录名  
						$this->deltree($pathdir.'/'.$a);  
					}  
				
					if ($this->is_empty_dir($pathdir.'/'.$a))  { //如果是空就直接删除  
						//记删除url到文件中 
						
						rmdir($pathdir.'/'.$a); 
					}  
				}  
			} 
			if ($this->is_empty_dir($pathdir.'/'.$a))  { //如果是空就直接删除  
						
				rmdir($pathdir.'/'.$a); 
			}  
			$d->close();  
		
		}  
	}  

	function is_empty_dir($pathdir)  
	{ 
		//判断目录是否为空 
		$d = opendir($pathdir);  
		$i = 0; 
		 
		while($a = readdir($d)) {  
		   $i++;  
		}  
		
		closedir($d);  
		
		if ($i > 2){
			return false;
		} else {
			return true;  
		}
	} 
     //删除目录
    function MakeDirectory($dir) {    
        return is_dir($dir) or (mkdir($dir, 0777, true) or ($this->MakeDirectory(dirname($dir)) and mkdir($dir, 0777)));
    }
    
    function rm($src, $dir = '') {
    	
        if (empty($dir)) {
            $dir = $this->dir;
        }
        
         $str_dir = substr_count($dir, '.') > 0 ? substr($dir, 1, strlen($dir)) : $dir;
          //记删除url到文件中        
         $this->getInsertFileUrl($str_dir, $src, 'del');

        return @unlink($dir . '/' . $src);
    }
    
    //记删除url到文件中
    function getInsertFileUrl($str_dir, $src, $type = 'del') {
    	
    	
		if ($type == 'del') {
			
			$str_dir = str_replace('./', '/', $str_dir);
			$str_dir = str_replace('//', '/', $str_dir);
			$str_dir = str_replace('//', '/', $str_dir.'/'.$src);
			$str_dir = $str_dir[0] == '/' ? $str_dir : '/'.$str_dir;
			$web_url =  $this->web_domain.$str_dir ;
			$server_path_url = $this->server_path.substr($str_dir, 1);
			insertFile($this->mCdnDeleteFile, $this->mCdnEditFile, $web_url, 'delete');
			insertFile($this->mDeleteFile, $this->mEditFile, $server_path_url, 'delete');
			
		} elseif ($type == 'edit') {
			
			$str_dir = $str_dir[0] == '/' ? $str_dir : '/'.$str_dir;
			$web_url =  $this->web_domain.$str_dir ;
			$server_path_url = $this->server_path.substr($str_dir, 1);

			insertFile($this->mCdnDeleteFile, $this->mCdnEditFile, $web_url, 'edit');
			insertFile($this->mDeleteFile, $this->mEditFile, $server_path_url, 'edit');
		}
		
    }
	
	// 单位自动转换函数
    function getRealSize($size)
    { 
        $kb = 1024;         // Kilobyte
        $mb = 1024 * $kb;   // Megabyte
        $gb = 1024 * $mb;   // Gigabyte
        $tb = 1024 * $gb;   // Terabyte
        
        if($size < $kb)
        { 
            return $size." B";
        }
        else if($size < $mb)
        { 
            return round($size/$kb,2)." KB";
        }
        else if($size < $gb)
        { 
            return round($size/$mb,2)." MB";
        }
        else if($size < $tb)
        { 
            return round($size/$gb,2)." GB";
        }
        else
        { 
            return round($size/$tb,2)." TB";
        }
    }

}
?>